
public class LSt2_3 {
    public static void main(String[] args) {
        //ListNode list1 = new ListNode(2, new ListNode(4, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9)))))));
        //ListNode list2 = new ListNode(9, new ListNode(9, new ListNode(9, new ListNode(9))));
        ListNode list1 = new ListNode();
        ListNode list2 = new ListNode();
        int arr[] = {2,4,3};
        int brr[] = {5,6,4};
        for (int a : arr) {
            list1.add(list1, a);
        }
        for (int a : brr) {
            list2.add(list2, a);
        }
        list1 = list1.next;
        list2 = list2.next;
        System.out.println(list1);
        System.out.println(list2);
        System.out.println("******");

        ListNode list = addTwoNumbers(list1, list2);
        System.out.println(list);

    }

    public static ListNode addTwoNumbers(ListNode list1, ListNode list2) {
        //解法一
        /*ListNode list = new ListNode(0);
        ListNode root = list;
        boolean f1 = false;
        boolean f2 = false;
        int k = 0;
        while (true) {
            int a = list1 == null ? 0 : list1.val;
            int b = list2 == null ? 0 : list2.val;
            int num = a + b + k;
            if (num > 9) {
                ListNode node = new ListNode(num % 10);
                root.next = node;
                root = node;
                k = 1;
            } else {
                ListNode node = new ListNode(num);
                root.next = node;
                root = node;
                k = 0;
            }
            if(!f1&&list1.next!=null){
                list1 = list1.next;
            }else {
                list1 = null;
                f1 = true;
            }
            if(!f2&&list2.next!=null  ){
                list2 = list2.next;
            }else {
                list2 = null;
                f2 = true;
            }
            if(k!=0){
                continue;
            }
            if(f1 && f2){
                break;
            }
        }
        return list.next;*/
        ListNode list = new ListNode(0);
        ListNode root = list;
        int k = 0;
        while (true) {
            if(list1==null && list2==null){
                break;
            }
            int a = list1 == null ? 0 : list1.val;
            int b = list2 == null ? 0 : list2.val;
            int num = a + b + k;
            ListNode node = new ListNode(num % 10);
            root.next = node;
            root = node;
            k = num / 10;
            if(list1!=null){
                list1 = list1.next;
            }
            if(list2!=null){
                list2 = list2.next;
            }
        }
        if(k>0){
            root.next = new ListNode(k);
        }
        return list.next;
    }
}
